package cn.com.czpb.client.module.news.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
//import android.webkit.JsResult;
//import android.webkit.WebChromeClient;
//import android.webkit.WebSettings;
//import android.webkit.WebView;
//import android.webkit.WebViewClient;

import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.MToolBarActivity;
import cn.com.czpb.client.model.event.PraiseEvent;
import cn.com.czpb.client.model.news.EmptyEntityList;
import cn.com.czpb.client.model.news.IsCollectionEntity;
import cn.com.czpb.client.model.news.NewsBean;
import cn.com.czpb.client.model.news.NewsDetailBean;
import cn.com.czpb.client.model.news.NewsDetailEntity;
import cn.com.czpb.client.model.news.PraiseNumEntity;
import cn.com.czpb.client.model.usercenter.LevelEntity;
import cn.com.czpb.client.module.dialog.ShareDialog;
import cn.com.czpb.client.module.personal.WodeFragment;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.TUtils;
import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/11/16.
 */

public class NewsHtmlActivity extends MToolBarActivity {
    @BindView(R.id.webview_id)
    WebView mywebview;
    @BindView(R.id.comment_number_tx)
    TextView commentNumberTx;
    @BindView(R.id.ll_newdetail_comments)
    LinearLayout llNewdetailComments;
    @BindView(R.id.praise_number_tx)
    TextView praiseNumberTx;
    @BindView(R.id.ll_newdetail_praise)
    LinearLayout llNewdetailPraise;
    @BindView(R.id.collection_number_tx)
    TextView collectionNumberTx;
    @BindView(R.id.ll_newdetail_collection)
    LinearLayout llNewdetailCollection;
    @BindView(R.id.share_number_tx)
    TextView shareNumberTx;
    @BindView(R.id.ll_newdetail_share)
    LinearLayout llNewdetailShare;
    @BindView(R.id.img_comment)
    ImageView imgComment;
    @BindView(R.id.img_praise)
    ImageView imgPraise;
    @BindView(R.id.img_collection)
    ImageView imgCollection;
    @BindView(R.id.img_share)
    ImageView imgShare;
    private NewsBean nb;
    private NewsDetailBean ndb;
    private String tid;

    @Override
    public void initView() {
        super.initView();
    }


    @Override
    protected int setLayoutId() {
        return R.layout.activity_newshtml;
    }

    @Override
    public void initData() {
//        Intent intent = getIntent();
//        String url = intent.getStringExtra("url");
        Intent intent = getIntent();
        nb = (NewsBean) intent.getSerializableExtra("newbean");
        tid = intent.getStringExtra("tid");
        getNewsDetails();




        WebSettings webSettings = mywebview.getSettings();
        String ua = webSettings.getUserAgentString();
        LogUtils.i("ua-->"+ua);
        webSettings.setUserAgentString(ua+"; gxrbapp/");
        String ua2 = webSettings.getUserAgentString();
        LogUtils.i("ua-->"+ua2);
        webSettings.setDisplayZoomControls(false);
        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
        webSettings.setAllowFileAccess(true); // 允许访问文件
        // 设置可以支持缩放
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        //扩大比例的缩放
        webSettings.setUseWideViewPort(true);
        //自适应屏幕
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setLoadWithOverviewMode(true);
//        mywebview.loadUrl("startAppSettings");

        mywebview.setWebViewClient(new WebViewClient(){
            @Override

            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                view.loadUrl(url);

                //如果不需要其他对点击链接事件的处理返回true，否则返回false

                return true;

            }
        });
        mywebview.setWebChromeClient(new MyWebChromeClient());
    }
    public class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult jsResult) {
            final JsResult finalJsResult = jsResult;
            new AlertDialog.Builder(view.getContext()).setMessage(message).setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finalJsResult.confirm();
                }
            }).setCancelable(false).create().show();
            return true;
        }
    }

    @OnClick({R.id.img_back, R.id.ll_newdetail_comments, R.id.ll_newdetail_praise, R.id.ll_newdetail_collection, R.id.ll_newdetail_share
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                if(mywebview != null && mywebview.canGoBack()){
                    mywebview.goBack();
                }else {
                    this.finish();
                }
                break;
            case R.id.ll_newdetail_collection:
                if (spu.getUser() != null) {
                    addCollection();
                } else {
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.ll_newdetail_share:
//                if(spu.getUser() != null) {
                    String img="";
                    if (nb.getImgs()!=null&&nb.getImgs().size()>0){
                        img = nb.getImgs().get(0);
                    }

                    ShareDialog dialog = new ShareDialog(activity, R.style.Sharedialog, nb.getTitle(), ndb.getNewsurl(),img, 0);
                    dialog.show();

//                }else{
//                    PageCtrl.start2LoginActivity(activity);
//                }
                break;
            case R.id.ll_newdetail_comments:
                if (spu.getUser() != null) {
                    if (ndb.getRtype().equals("5")) {
                        PageCtrl.startCommActivity(activity, ndb.getRvalue(), "1", "NEWS", ndb.getRvalue(), ndb);
                    } else {
                        PageCtrl.startCommActivity(activity, nb.getNid(), "1", "NEWS", nb.getNid(), ndb);
                    }
                } else {
                    PageCtrl.start2LoginActivity(activity);
                }
                break;
            case R.id.ll_newdetail_praise:
                praiseContent();
                break;

        }
    }
    /**
     * 获取新闻
     */
    // TODO: 2017/8/14
    private void getNewsDetails() {
        LogUtils.i("nid-->" + nb.getNid());
        Map<String, String> map = new HashMap<>();
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }
        map.put("nid", nb.getNid());
        map.put("device", DeviceUtils.getMyUUID(this));
        Factory.provideHttpService()
                .newsDetail(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsDetailEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsDetailEntity entity) {
                        LogUtils.i("detail-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsDetailEntity>() {
                    @Override
                    public void call(NewsDetailEntity entity) {
                        ndb = entity.data;
                        setNewsData();
                        addVisits(ndb.getTid());
                        Log.e("entity.data:",entity.data.toString());

                        if ("1".equals(entity.data.getIsfavorite())) {
                            imgCollection.setImageResource(R.drawable.tabbar_collect_light);
                        } else {
                            imgCollection.setImageResource(R.drawable.tabbar_collect);
                        }
                        if ("1".equals(entity.data.getIspraise())) {
                            imgPraise.setImageResource(R.drawable.tabbar_like_light);
                        } else {
                            imgPraise.setImageResource(R.drawable.tabbar_like);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("detail-->throwable-->" + throwable);
                    }
                });
    }
    // 设置新闻详情
    private void setNewsData() {

        //获取相关推荐新闻
        if (null == ndb) {
            return;
        }
        commentNumberTx.setText(ndb.getComcount());
        LogUtils.e("praisecount:"+ndb.getPraisecount());
        praiseNumberTx.setText(ndb.getPraisecount());
        collectionNumberTx.setText(ndb.getFavoritecount());
        String url = ndb.getNewsurl();
        mywebview.loadUrl(url);
        //TODO
    }

    //添加浏览量
    public void addVisits(String tid) {
        Map<String, String> map = new HashMap<>();
        map.put("nid", nb.getNid());
        map.put("type", nb.getRtype());
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("num", "1");
        map.put("tid", tid);

        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }

        map.put("device", DeviceUtils.getMyUUID(activity));
        Factory.provideHttpService().addvisit(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntityList, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntityList emptyEntityList) {
                        return true;
                    }
                })

                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntityList>() {
                    @Override
                    public void call(EmptyEntityList emptyEntityList) {
                        LogUtils.i("emptyEntityList----" + emptyEntityList.code);
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }

    // 添加收藏
    private void addCollection() {
        Map<String, String> map = new HashMap<>();
        map.put("typeid", nb.getNid());
        map.put("uid", spu.getUser().getUid());
        map.put("type", ndb.getRtype());
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .newsAddCollection(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<IsCollectionEntity, Boolean>() {
                    @Override
                    public Boolean call(IsCollectionEntity entity) {
                        LogUtils.i("200-->" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<IsCollectionEntity>() {
                    @Override
                    public void call(IsCollectionEntity entity) {
                        if ("200".equals(entity.code)) {
                            if ("1".equals(entity.data.getStatus())) {
                                TUtils.toast("收藏成功");
                                initlevel();
                                imgCollection.setImageResource(R.drawable.tabbar_collect_light);
                                collectionNumberTx.setText(entity.data.getFavcount());
                            } else {
                                imgCollection.setImageResource(R.drawable.tabbar_collect);
                                collectionNumberTx.setText(entity.data.getFavcount());
                                TUtils.toast("收藏取消");
                            }
                        } else {
                            TUtils.toast(entity.msg);
                        }
//                        setData();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                    }
                });
    }

    private void initlevel() {
        String uid = spu.getUser().getUid();
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        Factory.provideHttpService().MyLevel(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<LevelEntity, Boolean>() {
                    @Override
                    public Boolean call(LevelEntity levelEntity) {

                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<LevelEntity>() {
                    @Override
                    public void call(LevelEntity levelEntity) {
                        LogUtils.e("code--" + levelEntity.code);
                        if ("200".equals(levelEntity.code)) {
                            spu.getUser().setUlevel("Lv" + levelEntity.data.getUserinfo().getLevel());
                            Intent intent = new Intent();
                            intent.setAction(WodeFragment.ACTION_USER);
                            activity.sendBroadcast(intent);

                        } else {
                            TUtils.toast(levelEntity.msg);
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.e("throwable------" + throwable.getMessage());
                    }
                });
    }

    //赞
    private void praiseContent() {
        Map<String, String> map = new HashMap<>();
        if (spu.getUser() != null) {
            map.put("uid", spu.getUser().getUid());
        }
        map.put("device", DeviceUtils.getMyUUID(activity));
        map.put("nid", ndb.getNid());
        map.put("tid", ndb.getTid());
        map.put("type", ndb.getRtype());
        map.put("siteid", "1");
        LogUtils.i("type-->"+ndb.getRtype());
        Factory.provideHttpService().praiseContent(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<PraiseNumEntity>() {
                    @Override
                    public void call(PraiseNumEntity baseEntity) {
                        LogUtils.i("praise-->"+baseEntity.msg);
                        if ("200".equals(baseEntity.code)) {
                            imgPraise.setImageResource(R.drawable.tabbar_like_light);

                            String count = praiseNumberTx.getText().toString();
                            try{
                                int countNew = Integer.parseInt(count)+1;
                                praiseNumberTx.setText(countNew+"");
                            }catch (Exception e){
                                e.printStackTrace();
                            }

//                            praiseNumberTx.setText(baseEntity.data.getPraisecount());
                            PraiseEvent praiseEvent = new PraiseEvent();
                            praiseEvent.setNid(ndb.getNid());
                            praiseEvent.setPraisecount(baseEntity.data.getPraisecount());
                            EventBus.getDefault().post(praiseEvent);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("praise-->"+throwable);
                    }
                });

    }

    @Override
    public void finish() {
        super.finish();
        mywebview.loadUrl("about:blank");
    }
}
